﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Util;
using WAD.BLL;
using WAD.Client2.Ali;
using WAD.Client2.WXPay;
using WAD.DAL;
using Notify = Com.Alipay.Notify;

namespace WAD.WEB.Client2.Ali
{
    public partial class notify : System.Web.UI.Page
    {
        //支付宝异步回调处理
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary<string, string> sPara = GetRequestPost();
            string errMsg = "";
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                bool verifyResult = AlipaySignature.RSACheckV1(sPara,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.CHARSET,"RSA2",false);
                if (verifyResult)//验证成功
                {
                    var trade_no = sPara["trade_no"];         //支付宝交易号
                    var order_no = sPara["out_trade_no"];     //获取订单号(微街秀订单号)
                    var client = new DefaultAopClient(AlipayConfig.URL, AlipayConfig.APPID,
                  AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                  AlipayConfig.SIGNTYPE, AlipayConfig.ALIPAY_PUBLIC_KEY);
                    var request = new AlipayTradeQueryRequest();
                    var model = new AlipayTradeQueryModel();
                    model.OutTradeNo = order_no;
                    model.TradeNo = trade_no;
                    request.SetBizModel(model);
                    var res = client.Execute(request);
                    if (res.Code == "10000" && res.TradeStatus == "TRADE_SUCCESS")
                    {
                        FCOrderBLL.Pay_CallBack(order_no, res.TotalAmount, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Request.UserHostAddress, GetMsg(trade_no, order_no, res.BuyerLogonId, res.TotalAmount, Request.UserHostAddress), WAD.WEB.AppCode.WJXConfig.EncryptConfig.DES_KEY);
                        Response.Clear();
                        Response.Write("付款成功，请关闭当前页面！");
                        Response.End();
                    }

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    errMsg = string.Format("支付宝回调失败【签名错误: 订单号:{0},回调时间:{1}】", sPara["out_trade_no"], DateTime.Now);
                    Response.Write("fail");
                }
            }
            else
            {
                errMsg = string.Format("支付宝回调失败【无通知参数: 订单号:{0},回调时间:{1}】", sPara["out_trade_no"], DateTime.Now);
                Response.Write("无通知参数");
            }

            if (!string.IsNullOrEmpty(errMsg))
            {
                DaoLogcat.Add("pay", errMsg);
            }
        }


        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestPost()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }

            return sArray;
        }

        string GetMsg(string trade_no, string order_no, string buyer_email, string total_fee, string IP)
        {
            return "{\"trade_no\":\"" + trade_no + "\",\"order_no\":\"" + order_no + "\",\"buyer_email\":\"" + buyer_email + "\",\"total_fee\":\"" + total_fee + "\",\"IP\":\"" + IP + "\"}";
        }
    }
}